import { reqAddHospitalSet, reqGetHospitalSetById, reqUpdateHospitalSet } from "@/api/hospital/hospitalSet";
import { Button, Card, Form, Input, message, Space } from "antd";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function AddOrUpdateHospitalSet() {
  // 创建 form 对象
  let [form] = Form.useForm();
  //
  let [loading, setLoading] = useState<boolean>(false);
  //获取 navigate 函数
  const navigate = useNavigate();

  //声明函数 表单提交的回调
  const finish = async () => {
    try {
      //更新操作
      setLoading(true);
      //获取表单中的数据
      let data = form.getFieldsValue();
      if(id){
        //发送请求
        await reqUpdateHospitalSet({...data, id});
      }else{
        await reqAddHospitalSet(data);
      }
      //提示
      message.success((id ? '更新' : '添加') + "成功~~");
      //更新状态
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  const back = () => {
    navigate('/syt/hospital/hospitalSet');
  }

  //获取 id
  let {id} = useParams();
  
  //
  useEffect(() => {
    async function main(){
      //如果存在 id, 然后发送请求, 获取医院设置信息
      if(id){
        let result = await reqGetHospitalSetById(id);
        
        //将获取到的数据, 放到表单中, 进行呈现
        form.setFieldsValue(result);
      }
    } 
    main()
  }, [])

  return (
    <Card>
      <Form
        form={form}
        onFinish={finish}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        initialValues={{ remember: true }}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          //
          rules={[{ required: true, message: "医院名称不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "医院编号不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "api不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "联系人姓名不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: "联系人手机不能为空" },
            { pattern: /^1\d{10}$/, message: '手机号格式错误'}
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
          <Space>
            <Button loading={loading} type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={back}>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
